import { Displayer, isValidIP, isValidPort } from "./utils.js";
const toast = document.querySelector("#toast");
const toastText = document.querySelector("#toast .toast-body");
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toast);
const localIP = document.querySelector("#local-ip");
const localPort = document.querySelector("#local-port");
const targetIp = document.querySelector("#target-ip");
const targetPort = document.querySelector("#target-port");
// 自动加载下位机地址
targetIp.value = window.localStorage.getItem("targetIp");
targetPort.value = window.localStorage.getItem("targetPort");
const outputSwitch = document.querySelector("#output-switch");
const statusText = document.querySelector(".status-bar .status");
const progressDesc = document.querySelector("#progress-desc");
const progressPercent = document.querySelector("#progress-percent");
const progressBar = document.querySelector(".progress-bar");
// canvas初始化
const canvasGlobal = document.querySelector("#global-view");
const canvasLocal = document.querySelector("#local-view");
const ctxG = canvasGlobal.getContext("2d");
const ctxL = canvasLocal.getContext("2d");
const width = 800;
const height = 600;
canvasGlobal.width = canvasLocal.width = width;
canvasGlobal.height = canvasLocal.height = height;
const img = document.querySelector("main img");
// 用于动态展示左侧全局图像
let displayer = null;
// 是否收到上位机任务
let isReady = false;
// WebSocket连接
fetch("/local-ip")
  .then((res) => res.json())
  .then((data) => {
    localIP.value = data.ip;
    localPort.value = 3002;
    const socket = new WebSocket(
      `ws://${localIP.value}:${localPort.value}/msg`
    );
    socket.addEventListener("message", wsHandler);
  });

function wsHandler(e) {
  console.log("Message from server ", e.data);
  // 命令处理
  const cmdArgs = e.data.split(" ");
  switch (cmdArgs[0]) {
    // 页面展示运动估计
    case "show":
      isReady = true;
      statusText.classList.add("ready");
      statusText.textContent = `已收到任务：场景${cmdArgs[3]}，轨迹类型${cmdArgs[1]}`;
      progressDesc.textContent = "图像采集中...";
      displayTraj(cmdArgs[3], cmdArgs[1]);
      break;
    // 页面展示图像发送进度
    case "tran":
      if (cmdArgs[1] !== "done") {
        progressDesc.textContent = "图像发送中...";
        progressPercent.textContent = `${cmdArgs[1]}%`;
        progressBar.style.width = `${cmdArgs[1]}%`;
      } else {
        progressDesc.textContent = "图像发送完成";
      }
      break;
  }
}

// 展示拍摄轨迹
async function displayTraj(scene, traj) {
  // 先裁剪图片
  const data = await fetch(`/cut-image?time=${new Date().getTime()}`).then(
    (res) => res.json()
  );
  if (data.code !== 0) {
    console.log(data.message);
    return;
  }

  img.src = `images/scenes/${scene}.jpg`;
  img.onload = () => {
    displayer = new Displayer(traj, ctxG, ctxL, width, height, img);

    // 动画播放拍摄轨迹
    const it = setInterval(() => {
      if (displayer.done) {
        clearInterval(it);
        // 如果自动发送打开，则自动向下位机发送图片
        if (outputSwitch.checked) {
          transImages();
        }
        return;
      }
      displayer.displayNextFrame();
      const percentage = displayer.getPercentage();
      progressPercent.textContent = `${percentage}%`;
      progressBar.style.width = `${percentage}%`;
    }, 50);
  };
}

// 向下位机发送图片
function transImages() {
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ip: targetIp.value,
      port: targetPort.value,
    }),
  };
  fetch("/tran-image", options)
    .then((res) => res.json())
    .then((data) => {
      if (data.code === 0) {
        // 保存下位机地址
        window.localStorage.setItem("targetIp", targetIp.value);
        window.localStorage.setItem("targetPort", targetPort.value);
      } else {
        // 显示错误信息
        toastText.textContent = data.message;
        toastBootstrap.show();
        // 恢复状态
        outputSwitch.checked = false;
        targetIp.removeAttribute("disabled");
        targetPort.removeAttribute("disabled");
      }
    });
}

// 自动发送开关
outputSwitch.addEventListener("change", () => {
  if (outputSwitch.checked) {
    if (!isValidIP(targetIp.value)) {
      toastText.textContent = "请输入正确的IP地址";
      toastBootstrap.show();
      outputSwitch.checked = false;
      return;
    }
    if (!isValidPort(targetPort.value)) {
      toastText.textContent = "请输入正确的端口号";
      toastBootstrap.show();
      outputSwitch.checked = false;
      return;
    }
    targetIp.setAttribute("disabled", true);
    targetPort.setAttribute("disabled", true);
    // 具备状态则向下位机发送图片
    if (isReady) {
      transImages();
    }
  } else {
    targetIp.removeAttribute("disabled");
    targetPort.removeAttribute("disabled");
  }
});
